// 判断对象是否为空
function isNoNull(obj){
  if (obj != null && obj != undefined && obj != '') {
    return true;
  }  else {
    return false;
  }
}

// 字符串转int数组
function strToIntArray(str){
  let arry = new Array();
  if(str != '' && str != null && str != undefined){
    let vals = str.split(",")
    vals.forEach(v => {
      arry.push(parseInt(v))
    })
  }
  return arry;
}

// 把数组用字符 c 连接成字符串
function arrayToStr(obj, c){
  if(obj != '' && obj != null && obj != undefined){
    if (obj instanceof Array) {
      return obj.join(c)
    } else {
      return obj;
    }
  } else {
    return "";
  }
}

// 根据ID在数组中查找对象
function findObjFromArrayById(array, id){
  for(let i = 0; i < array.length; i++){
    if(array[i].id == id){
      return array[i];
    }
  }
}

// 兼容 IE跟safari 的字符串转日期函数
function getDateByString(str){
  var arr = str.split(/[- : \/]/);
  switch(arr.length){
    case 1:
      return new Date(arr[0]);
    case 2:
      return new Date(arr[0], arr[1]-1);
    case 3:
      return new Date(arr[0], arr[1]-1, arr[2]);
    case 4:
      return new Date(arr[0], arr[1]-1, arr[2], arr[3]);
    case 5:
      return new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4]);
    default:
      return new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
  }
}

//几年（n）后的今天的前一天
function someYearPast(time, n) {
  //var time=new Date();
  var year = time.getFullYear() + n;
  var month = time.getMonth() + 1;
  var day = time.getDate();
  if (month < 10) {
    month = "0" + month;
  }

  if (day > 1) {
    day = day - 1;
  } else {
    month = month - 1;
    console.log(month);
    if (month < 10) {
      month = "0" + month;
    }
    if (month == 0) {
      month = 12;
    }
    day = new Date(year, month, 0).getDate();
  }

  var v2 = year + '-' + month + '-' + day;
  return getDateByString(v2);
}

//几个月（n）后的今天的前一天
function someMonthPast(time, n) {
  //var time=new Date();
  var year = time.getFullYear();
  var month = time.getMonth() + 1;
  var day = time.getDate();
  if(month + n > 12){
    year = year + 1;
    month = month + n - 12;
  } else {
    month = month + n;
  }
  if (month < 10) {
    month = "0" + month;
  }

  if (day > 1) {
    day = day - 1;
  } else {
    month = month - 1;
    console.log(month);
    if (month < 10) {
      month = "0" + month;
    }
    if (month == 0) {
      month = 12;
    }
    day = new Date(year, month, 0).getDate();
  }

  var v2 = year + '-' + month + '-' + day;
  return getDateByString(v2);
} 

// 时间戳（毫秒）转字符串。 format格式 yyyy-MM-dd hh:mm:ss
function timestampToTime (millisecond, format){
  if(millisecond > 0){
    var date = new Date(millisecond) //毫秒
    return date.format(format)
  } else {
    return '';
  }
}

// 俩时间比较（Date类型）
// date1 > date2，则返回相差毫秒数（正数）
// date1 = date2，则返回 0 
// date1 < date2，则返回相差毫秒数（负数）
function dateCompare(date1, date2) {
  return date1.getTime() - date2.getTime();
}

// 日期类型格式转换
// yyyy-MM-dd hh:mm:ss
Date.prototype.format = function(format) {
  var date = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "h+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "q+": Math.floor((this.getMonth() + 3) / 3),
    "S+": this.getMilliseconds()
  };
  if (/(y+)/i.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (var k in date) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1
        ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
    }
  }
  return format;
}

// 获取指定长度（len），进制（2,8,10,16,32）的UUID
function uuid(len, radix) {
  var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  var uuid = [], i;
  radix = radix || chars.length;

  if (len) {
    // Compact form
    for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
  } else {
    // rfc4122, version 4 form
    var r;

    // rfc4122 requires these characters
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';

    // Fill in random data. At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | Math.random()*16;
        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
      }
    }
  }

  return uuid.join('');
}

// 得到url上的参数
function getQueryVariable(variable){
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if(pair[0] == variable){return pair[1];}
  }
  return(false);
}

// 得到url上的参数
function getQueryIntVariable(variable){
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if(pair[0] == variable){return parseInt(pair[1]);}
  }
  return(0);
}

// 得到文件大小的字符串描述
function getFileSizeStr(size){
  if(size > 1000000000){
    return (size / (1024 * 1024 * 1024)).toFixed(2) + "G";
  } else if(size > 1000000){
    return (size / (1024 * 1024)).toFixed(2) + "M";
  } else if(size > 1000){
    return (size / 1024).toFixed(2) + "K";
  } else {
    return size + "B";
  }
}

// 把 json 数据导出excel
// dataFormat 格式如: {
//           "title":{
//             title: "保单标题",
//             format: function(row){
//               return row;
//             }
//           },
//           "company_nickname":{
//             title: "保险公司",
//             width: 20,
//           }}
function exportExcelByConfig(dataFormat, jsonData){
  let header = [];
  let title = [];
  let colsWidth = [];
  for (let key in dataFormat) {
    header.push(key);
    title.push(dataFormat[key].title);
    if(dataFormat[key].width){
      colsWidth.push({wch:dataFormat[key].width})
    } else {
      colsWidth.push({wch:10}) // 默认宽度 10 个英文字符
    }
  }

  // 过滤数据，把需要的提取出来
  let data = [];
  jsonData.forEach(item => {
    let row = {};
    for (let key in item) {
      if (dataFormat.hasOwnProperty(key)) {
        if(dataFormat[key].format){
          row[key] = dataFormat[key].format(item[key]);
        } else {
          row[key] = item[key];
        }
      }
    }
    data.push(row);
  });

  // 新建空workbook，然后加入worksheet
  let ws = XLSX.utils.json_to_sheet(data, {
    header:header,
    dateNF:"yyyy-MM-dd",
  });

  // 设置列宽
  ws["!cols"] = colsWidth;


  // 修改表头(把表头的字母还为中文title)
  const range = XLSX.utils.decode_range(ws['!ref']);
  for(let c = range.s.c; c <= range.e.c; c++) {
    const header = XLSX.utils.encode_col(c) + '1';
    ws[header].v = title[c];
  }

  let wb = XLSX.utils.book_new();/*新建book*/
  XLSX.utils.book_append_sheet(wb, ws, "sheet1");/* 生成xlsx文件(book,sheet数据,sheet命名) */
  XLSX.writeFile(wb, "sheetjs.xlsx");/*写文件(book,xlsx文件名称)*/
}


/**
 * 压缩图片,返回图片画板（canvas）
 * @param img 被压缩的img对象
 * @param type 压缩后转换的文件类型(如: image/png )
 * @param mx 触发压缩的图片最大宽度限制
 * @param mh 触发压缩的图片最大高度限制
 */
function compressImg(img, type, mx, mh) {
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    const { width: originWidth, height: originHeight } = img;
    // 最大尺寸限制
    const maxWidth = mx;
    const maxHeight = mh;
    // 目标尺寸
    let targetWidth = originWidth;
    let targetHeight = originHeight;
    if (originWidth > maxWidth || originHeight > maxHeight) {
      if (originWidth / originHeight > 1) {
        // 宽图片
        targetWidth = maxWidth;
        targetHeight = Math.round(maxWidth * (originHeight / originWidth));
      } else {
        // 高图片
        targetHeight = maxHeight;
        targetWidth = Math.round(maxHeight * (originWidth / originHeight));
      }
    }
    canvas.width = targetWidth;
    canvas.height = targetHeight;
    context.clearRect(0, 0, targetWidth, targetHeight);
    // 图片绘制
    context.drawImage(img, 0, 0, targetWidth, targetHeight);
    return canvas;
}

/**
 * 填充图片,返回图片画板（canvas）
 * @param img  img对象
 * @param type 转换的文件类型(如: image/png )
 */
function fullImg(img, type){
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');
  const { width: originWidth, height: originHeight } = img;
  canvas.width = originWidth;
  canvas.height = originHeight;
  context.clearRect(0, 0, originWidth, originHeight);
  // 图片绘制
  context.drawImage(img, 0, 0, originWidth, originHeight);
  return canvas;
}